package com.kele.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.kele.auth.feign.UserFeignClient;
import com.kele.auth.model.dto.AuthParam;
import com.kele.auth.model.dto.UserExt;
import com.kele.auth.service.AuthService;
import com.kele.base.common.constant.Auth;
import com.kele.base.common.exception.AppException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @Author: Kele
 * @CreateDate: 2023/4/22 19:51
 * @Version:
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserDetailServiceImpl.class);

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        AuthParam authParam = null;

        try {
            authParam = JSON.parseObject(username, AuthParam.class);
        } catch (Exception e) {
            logger.info("认证请求数据格式不对", e);
            AppException.cast("认证请求数据格式不对");
        }

        // 认证方式
        String authType = authParam.getAuthType();
        if (!Auth.AuthType.isInclude(authType)) {
            // 认证方式错误
            AppException.cast("认证方式错误");
        }

        AuthService authService = applicationContext.getBean(authType + "_authService", AuthService.class);

        // 认证
        UserExt result = authService.execute(authParam);

        return getPrincipal(result);
    }
    /**
     * 封装用户信息
     * @param userExt 用户信息拓展类
     * @return org.springframework.security.core.userdetails.UserDetails
     * @author: Kele
     * @date 2023/4/17 22:01
     */
    private UserDetails getPrincipal(UserExt userExt){
        String password = userExt.getPassword();

        //        String[] authorities = {"test"};
        List<String> authoritiesByUserId = userFeignClient.getAuthorities(userExt.getId());
        String[] authorities = authoritiesByUserId.toArray(new String[0]);

        userExt.setPassword(null);
        return User.withUsername(JSON.toJSONString(userExt)).password(password).authorities(authorities).build();
    }

}
